const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
const cors = require("cors");
// const router = express.Router()
// 引入 接口文件集合
const requestHandler = require("./handle");

// 引入 路由映射
const routeMap = require("./routes");

// 使用body-parser中间件
app.use(
  bodyParser.urlencoded({
    extended: false,
  })
);
app.use(bodyParser.json());

// DB config
const db = require("./config/keys").mogoURL;

// connect to mogodb
mongoose.connect(db).then(
  () => {
    console.log("连接成功");
    // requestHandler['setPinyin']()
  },
  (err) => {
    console.log(err);
  }
);

const getHandler = (key) => {
  return requestHandler[key];
};

//拦截所以api接口设置头部信息（不能放底部，why？）
app.all("*", function (req, res, next) {
  //跨域
  res.header(
    "Access-Control-Allow-Origin",
    req.headers["origin"] || "http://192.168.101.16:9000"
  );
  res.header(
    "Access-Control-Allow-Headers",
    "token,Content-Type,Content-Length, Authorization, Accept,X-Requested-With,domain,zdy"
  );
  // //设置前端的这些ajax请求方法'GET,POST,PUT,HEAD,DELETE,OPTIONS'，都有权限调接口
  res.header("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
  res.header("Access-Control-Allow-Credentials", true);
  // console.log(req.url,'前端传进来的参数为===：',req.method == 'GET'?req.query:req.body)
  // console.log(req.url)
  if ("OPTIONS" == req.method) {
    res.sendStatus(200);
  } else {
    let requestName = req.url.replace("/api", "");
    let route = routeMap[requestName] || {};
    let handler = getHandler(route.handler);
    if (typeof handler === "function") {
      if (route.needVerify) {
        requestHandler.verifyLogin(req, res, handler);
      } else {
        handler(req, res);
      }
    } else {
      getHandler("noHandler")(req, res);
    }
    return;
  }
});
const port = process.env.port || 5201;

app.listen(port, () => {
  console.log(`Server runing on port: ${port}`);
});
